<script setup lang="ts">
import {ref,computed} from 'vue' 
import { useRouter } from 'vue-router';
import {verifyCode,isCode} from '@/api/user';
import { showDialog,showSuccessToast, showFailToast } from 'vant';

//验证码
const telcode=ref('')
//变量记录倒计时时间
const time=ref(10)
// 路由
const router=useRouter()
// 验证码获取按钮文本
const text=ref('发送验证码')
//电话号码
const tel=JSON.parse(localStorage.getItem('Tel'))


//判断输入验证码长度是否符合条件
const flag=computed(()=>{
    return telcode.value.length==5
})

// 设置倒计时
let timer:any=null;

function setTIme(){
    //清除前一个定时器
    clearInterval(timer)

    //发送请求获取验证码
    verifyCode({tel: tel}).then(res=>{
        if(res.data.code==200){
            showDialog({
                message: `${res.data.message}，你的验证码为${res.data.data}`,
                }).then(() => {});
        }else{
            showDialog({ message: '发送请求失败，请重新发送' });        
        }
    })

    //设置倒计时
    timer=setInterval(()=>{
        text.value=time.value+'s 后重新获取'
        time.value--
        if(time.value==0){
            //关闭定时器
            clearInterval(timer)
            //回复时间、按钮内容
            time.value=10
            text.value='获取验证码'
        }
    },1000)
}

//提交表单
function onSubmit(){
    isCode({tel: tel,telcode:telcode.value}).then(res=>{
        if(res.data.code==200){
            showSuccessToast('验证通过');
            router.push('/register/step3')
        }else{
            showFailToast('验证失败，请重新验证！')
        }
    })
}

</script>



<template>
<van-form  @submit="onSubmit">
            <van-cell-group inset>
                <van-field v-model="telcode" name="验证码" label="验证码" placeholder="请输入验证码" :rules="[{ required: true,message: '请填写正确的验证码'}]">
                <template #button>
                <van-button @click="setTIme"  :disabled="time!=10" size="small">{{text}}</van-button> 
                </template>
                </van-field>
                
            </van-cell-group>
            <div style="margin: 30px 16px 16px 16px;">
                <van-button :disabled="!flag" round block color="#f66" native-type="submit">
                下一步
                </van-button>
            </div>
    </van-form>
</template>